﻿using System;
using System.Collections.Generic;
using System.Linq;
using Fsxm.LispEdit;
using System.Net;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;
using System.Collections;
using Fsxm.Net;

[assembly: PluginClass(typeof(Plugin_LibAutoUpdate.LibAutoUpdate))]

namespace Plugin_LibAutoUpdate
{
    public class LibAutoUpdate : Plugin
    {
        private static string funlib = @"https://gitee.com/vicwjb/abfl/raw/master/";
        private static string userlib = GetLibPath();
        public override void Start()
        {
            //更新函数库
            var item = AddMenuItem("更新函数库", null);
            item.Click += item_Click;



        }


        //定义动作函数
        private void item_Click(object sender, EventArgs e)
        {
            var re = MessageBox.Show("选择是否更新函数库", "更新个人函数库", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            if (re == DialogResult.Yes)
            {
                //string userlib = GetLibPath();
                //string funlib = @"https://gitee.com/vicwjb/abfl/raw/master/";

                if (CompareUpdateTime())
                {
                    MessageBox.Show("函数库为最新版本，无需更新！", "更新个人函数库", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    DownLoadLib(funlib, userlib, getUpdateFiles(Path.GetTempPath()));
                    MessageBox.Show("函数库更新完毕，请尽情使用！", "更新个人函数库", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("太可惜了！", "更新个人函数库", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        //获取函数库保存目录
        private static string GetLibPath()
        {
            //PathHelp.MakeAbsolutePath(Application.StartupPath, Options.LoadXml().UserLib);
            string savepath = Path.Combine(PathHelp.MakeAbsolutePath(Application.StartupPath, Options.LoadXml().UserLib), "abfl");
            Directory.CreateDirectory(savepath);
            return savepath;
        }
        //下载函数
        private void DownLoadLib(string pathfrom, string pathto, string[] filelist)
        {
            //    WebClient myWebClient = new WebClient();//定义全局下载对象
            //    myWebClient.Headers.Add("User-Agent", "Microsoft Internet Explorer");
            //myWebClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
            //myWebClient.Headers.Add("Content-Type", "application / zip, application / octet - stream");
            //myWebClient.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            //myWebClient.Headers.Add("Referer", "http://Something");
            //myWebClient.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            //Directory.CreateDirectory(pathto);
            foreach (var item in filelist)
            {
                WebClient myWebClient = new WebClient();//定义全局下载对象
                myWebClient.Headers.Add("User-Agent", "Microsoft Internet Explorer");
                try
                {
                    myWebClient.DownloadFile(Path.Combine(pathfrom, item), Path.Combine(pathto, item));
                    
                }
                catch (Exception)
                {

                }
                finally
                {
                    if (myWebClient != null)
                    {
                        myWebClient.Dispose();
                    }
                }

            }
        }
        //最近一次更新日期
        private string GetTheLastUpdateTime(string Dir)
        {
            
            string LastUpdateTime = "";
            string AutoUpdaterFileName = Path.Combine(Dir, @"update.xml");
            if (!File.Exists(AutoUpdaterFileName))
                return LastUpdateTime;

            XElement root = XElement.Load(AutoUpdaterFileName);
            LastUpdateTime = (string)
                (from el in root.Descendants("UpdateTime")
                 select el.Attribute("Date")).First();

            return LastUpdateTime;
        }
        //判断更新日期是否一致
        private bool CompareUpdateTime()
        {
            WebClient WebClient = new WebClient();
            WebClient.Headers.Add("User-Agent", "Microsoft Internet Explorer");
            string from = funlib + @"update.xml";
            string to = Path.GetTempPath() + @"update.xml";
            //to = to + @"\\update.xml";
            WebClient.DownloadFile(from, to);

            string lasttime1 = GetTheLastUpdateTime(GetLibPath());
            string lasttime2 = GetTheLastUpdateTime(Path.GetTempPath());
            return lasttime1 == lasttime2;
        }


        //获取更新文件列表
        private string[] getUpdateFiles(string dir)
        {
            ArrayList fileupdatelist = new ArrayList();

            XElement filename = XElement.Load(dir + @"\update.xml");
            IEnumerable<XElement> items =
                from el in filename.Descendants("UpdateFile")
                select el;
            foreach (XElement prdName in items)
            {
                fileupdatelist.Add((string)prdName);
            }
            string[] filelist = (string[])fileupdatelist.ToArray(typeof(string));
            return filelist;
        }

    }
}
